<template>
  <div class="layui-container">
    <Panel></Panel>
  <div class="layui-row layui-col-space15">
    <div class="layui-col-md8 content detail">
      <div class="fly-panel detail-box">
        <h1>{{page.title}}</h1>
        <div class="fly-detail-info">
          <!-- <span class="layui-badge">审核中</span> -->
          <!-- ask-提问，advise-建议，discuss-交流，share-分享，logs-动态，notice-公告 -->
          <span class="layui-badge layui-bg-green fly-detail-column" v-if="page.catalog === 'logs'">动态</span>
          <span class="layui-badge layui-bg-green fly-detail-column" v-else-if="page.catalog === 'ask'">提问</span>
          <span class="layui-badge layui-bg-green fly-detail-column" v-else-if="page.catalog === 'advise'">建议</span>
          <span class="layui-badge layui-bg-green fly-detail-column" v-else-if="page.catalog === 'discuss'">交流</span>
          <span class="layui-badge layui-bg-green fly-detail-column" v-else-if="page.catalog === 'share'">分享</span>
          <span class="layui-badge layui-bg-green fly-detail-column" v-else-if="page.catalog === 'notice'">公告</span>

          <span class="layui-badge" style="background-color: #999;" v-if="page.isEnd === 0">未结</span>
          <span class="layui-badge" style="background-color: #5FB878;" v-else>已结</span>

          <span class="layui-badge layui-bg-black" v-if="page.isTop === 1">置顶</span>
          <template v-if="page.tags">
            <span class="layui-badge layui-bg-red" :class="tag.class" v-for="(tag,index) in page.tags" :key="'tag'+index">{{tag.name}}</span>
          </template>
          <div v-hasRole="'admin'">
            <div class="fly-admin-box" data-id="123">
              <span v-hasPermission="'delete'" class="layui-btn layui-btn-xs jie-admin" type="del">删除</span>

              <span v-if="page.isTop === 0" class="layui-btn layui-btn-xs jie-admin" type="set" field="stick" rank="1">置顶</span>
              <span v-else class="layui-btn layui-btn-xs jie-admin" type="set" field="stick" rank="0" style="background-color:#ccc;">取消置顶</span>
<!--
              <span class="layui-btn layui-btn-xs jie-admin" type="set" field="status" rank="1">加精</span>
              <span class="layui-btn layui-btn-xs jie-admin" type="set" field="status" rank="0" style="background-color:#ccc;">取消加精</span> -->
            </div>
          </div>
          <span class="fly-list-nums">
            <a href="#comment"><i class="iconfont" title="回答">&#xe60c;</i> {{page.answer}}</a>
            <i class="iconfont" title="人气">&#xe60b;</i> {{page.reads}}
          </span>
        </div>
        <div class="detail-about">
          <a class="fly-avatar" href="../user/home.html">
            <img :src="page.user?page.user.pic:'https://tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg'" alt="贤心">
          </a>
          <div class="fly-detail-user">
            <a href="../user/home.html" class="fly-link">
              <cite>{{page.user?page.user.name:''}}</cite>
              <!-- <i class="iconfont icon-renzheng" title="认证信息"></i> -->
              <i class="layui-badge fly-badge-vip" v-if="page.user?page.user.isVip:false">VIP{{page.user.isVip}}</i>
            </a>
            <span>{{page.created}}</span>
          </div>
          <div class="detail-hits" id="LAY_jieAdmin" data-id="123">
            <span style="padding-right: 10px; color: #FF7200">悬赏：{{page.favs}}</span>
          </div>
        </div>
        <div class="layui-btn-container fly-detail-admin pt1">
          <router-link :to="{name: 'edit' ,params : {tid: tid , page: page}}" class="layui-btn layui-btn-sm jie-admin" v-show="page.isEnd === 0 && user._id === page.user._id">编辑</router-link>
          <a href="javascript:;" class="layui-btn layui-btn-sm jie-admin-collect" :class="{'layui-btn-primary': page.collect}" @click.prevent="collect()">{{page.collect?'取消收藏':'收藏'}}</a>
        </div>
        <div class="detail-body photos" v-html="this.content">

        </div>
      </div>

      <div class="fly-panel detail-box" id="flyReply">
        <fieldset class="layui-elem-field layui-field-title" style="text-align: center;">
          <legend>回帖</legend>
        </fieldset>

        <ul class="jieda" id="jieda">
          <template v-for="(item,index) in comments" >
          <li data-id="111" class="jieda-daan" v-if="item.cuid" :key ="'comment' + index">
              <a name="item-1111111111"></a>
            <div class="detail-about detail-about-reply">
              <router-link :to="{'name' : 'home',params: {uid: item.cuid._id}}" class="fly-avatar">
                <img :src="item.cuid.pic" alt=" ">
              </router-link>
              <div class="fly-detail-user">
                <router-link :to="{'name' : 'home',params: {uid: item.cuid._id}}" class="fly-link">
                  <cite>{{item.cuid.name}}</cite>
                  <!-- <i class="iconfont icon-renzheng" title="认证信息：XXX"></i> -->
                  <i class="layui-badge fly-badge-vip" v-if="item.cuid.isVip">VIP{{item.cuid.isVip}}</i>
                </router-link>

                <span v-if="index===0">(楼主)</span>
                <!--
                <span style="color:#5FB878">(管理员)</span>
                <span style="color:#FF9E3F">（社区之光）</span>
                <span style="color:#999">（该号已被封）</span>
                -->
              </div>

              <div class="detail-hits">
                <span>{{item.created | formatDate}}</span>
              </div>

              <i class="iconfont icon-caina" title="最佳答案" v-if="item.isBest === 1"></i>
            </div>
            <div class="detail-body jieda-body photos" v-richtext="item.content">
            </div>
            <div class="jieda-reply">
              <!-- zanok -->
              <span class="jieda-zan" :class="{zanok: item.handed === 1}" type="zan" @click="hand(item)">
                <i class="iconfont icon-zan"></i>
                <em>{{item.hands}}</em>
              </span>
              <span type="reply" @click='replyComment(item)'>
                <i class="iconfont icon-svgmoban53"></i>
                回复
              </span>
              <div class="jieda-admin">
                <span type="edit" v-if="page.isEnd===0 && user._id === item.cuid._id" @click="editContent(item)">编辑</span>
                <!-- <span type="del">删除</span> -->
                <span class="jieda-accept" type="accept" v-if="page.isEnd === 0 && user._id === page.user._id" @click="setBest(item)">采纳</span>
              </div>
            </div>

          </li>
          </template>
          <!-- 无数据时 -->
          <li class="fly-none" v-if="comments.length === 0">消灭零回复</li>
        </ul>
        <Pagination v-show="comments.length > 0 && total > 0" @changeCurrent="changeCurrent" :total="total" :size="size" :current="current" :showEnd="false" :showType="'icon'"></Pagination>
        <div class="layui-form layui-form-pane">
          <form>
            <ValidationObserver ref="observer" v-slot="{validate}">
            <Editor :initContent="replyContent" @add="getContent"></Editor>
            <div class="layui-form-item">
              <label class="layui-form-label">验证码</label>
              <ValidationProvider name="code" rules="required|length:4" v-slot="{errors}">
                <div class="layui-input-inline">
                  <input
                    type="text"
                    name="code"
                    v-model="code"
                    placeholder="请输入标题"
                    autocomplete="off"
                    class="layui-input"
                  />
                </div>
                <span class="svg" @click="getCaptcha()" v-html="svg"></span>
                <div class="form-error">{{errors[0]}}</div>
              </ValidationProvider>
            </div>
            <div class="layui-form-item">
              <button class="layui-btn" type="button" @click="validate().then(submit)">提交回复</button>
            </div>
            </ValidationObserver>
          </form>
        </div>
      </div>
    </div>
    <div class="layui-col-md4">
      <HotList></HotList>
      <Abs></Abs>
      <Links></Links>
    </div>
  </div>
</div>
</template>

<script>
import { getDetail } from '@/api/content'
import { getComments, addComment, updateComment, setBestComment, addHands } from '@/api/comments'
import { setCollect } from '@/api/user'
import HotList from '@/components/sidebar/HotList'
import Abs from '@/components/sidebar/Abs'
import Links from '@/components/sidebar/Links'
import Panel from '@/components/Panel'
import Editor from '@/components/modules/editor'
import Pagination from '@/components/modules/pagination/pagination'
import codeMix from '@/mixin/code'
import { escapeHtml } from '@/util/escapeHtml'
import { scrollToElem } from '@/util/common'

export default {
  mixins: [codeMix],
  name: 'detail',
  props: ['tid'],
  components: {
    HotList,
    Abs,
    Links,
    Panel,
    Editor,
    Pagination
  },
  watch: {
    tid (newval, oldval) {
      if (newval !== oldval) {
        this.getPostDetail()
        this.getCommentsList()
      }
    }
  },
  data () {
    return {
      current: 0,
      size: 5,
      total: 0,
      page: {

      },
      editInfo: {},
      comments: [],
      replyContent: ''
    }
  },
  computed: {
    content () {
      if (this.page.content && this.page.content.trim() !== '') {
        return escapeHtml(this.page.content)
      }
      return ''
    },
    user () {
      return this.$store.state.userInfo
    }
  },
  mounted () {
    this.getPostDetail()
    this.getCommentsList()
  },
  methods: {
    // 设置收藏
    async collect () {
      const isLogin = this.$store.state.isLogin
      if (isLogin) {
        const result = await setCollect({
          tid: this.page._id,
          title: this.page.title
        })
        if (result.code === 200) {
          this.page.collect = result.data
        }
        this.$pop('', result.msg)
      } else {
        this.$pop('shake', '请先登录再进行收藏')
      }
    },
    // 回复评论
    replyComment (item) {
      const name = item.cuid.name
      if (this.replyContent) {
        const reg = /@(\S+\s)/g
        if (reg.test(this.replyContent)) {
          this.replyContent = this.replyContent.replace(reg, `@${name} `)
        } else {
          this.replyContent = `@${name} ${this.replyContent}`
        }
      } else {
        this.replyContent = `@${name} `
      }
      scrollToElem('.layui-input-block', 1000, -65)
      document.getElementById('edit').focus()
    },
    // 点赞
    async hand (item) {
      if (item.handed === 1) {
        return
      }
      if (!this.$store.state.isLogin) {
        this.$pop('shake', '请先登录再进行点赞')
        return
      }
      const res = await addHands({
        id: item._id
      })
      if (res.code === 200) {
        item.handed = 1
        item.hands++
      }
      this.$pop('', res.msg)
    },
    // 设置最佳
    setBest (item) {
      this.$confirm('确定要将此评论设置为最佳答案吗？', async () => {
        const result = await setBestComment({
          tid: this.tid,
          id: item._id
        })
        if (result.code === 200) {
          this.page.isEnd = 1
          item.isBest = 1
        }
        this.$pop('', result.msg)
      })
    },
    // 编辑评论
    editContent (item) {
      this.editInfo = item
      this.replyContent = item.content
      scrollToElem('.layui-input-block', 1000, -65)
      document.getElementById('edit').focus()
    },
    // 提交
    async submit () {
      const valid = await this.$refs.observer.validate()
      if (!valid) {
        return
      }
      if (!this.$store.state.isLogin) {
        this.$pop('shake', '请先登录再进行评论')
        return
      }
      if (this.replyContent.trim() === '') {
        this.$pop('shake', '评论内容不能为空')
        return
      }
      const sendData = {
        content: this.replyContent,
        tid: this.tid,
        sid: this.$store.state.sid,
        code: this.code
      }
      let result = {}
      if (this.editInfo.cuid) {
        sendData.cid = this.editInfo.cuid._id
        sendData.id = this.editInfo._id
        if (this.replyContent.trim() === this.editInfo.content.trim()) {
          this.$pop('shake', '编辑内容不能和之前的相同！')
          return
        }
        result = await updateComment(sendData)
      } else {
        result = await addComment(sendData)
      }

      if (result.code === 200) {
        // 更新操作
        if (this.editInfo.cuid) {
          this.editInfo.content = this.replyContent
          this.comments.splice(this.comments.indexOf(this.editInfo), 1, this.editInfo)
          this.editInfo = {}
        } else { // 新增
          const { _id, pic, name, isVip, status } = this.$store.state.userInfo
          const cuid = {
            _id, pic, name, isVip, status
          }
          result.data.cuid = cuid
          this.comments.push(result.data)
        }
        this.replyContent = ''
        this.code = ''
        this.getCaptcha()
        this.$refs.observer.reset()
      }
      this.$pop('', result.msg)
    },

    getContent (content) {
      this.replyContent = content
    },
    changeCurrent (val, limit) {
      this.current = val
      this.limit = limit
      this.getCommentsList()
    },
    async getPostDetail () {
      const result = await getDetail(this.tid)
      if (result.code === 200) {
        this.page = result.data
      } else {
        this.$alert(result.msg)
      }
    },
    async getCommentsList () {
      const res = await getComments({
        tid: this.tid,
        page: this.current,
        limit: this.limit
      })
      console.log(res)
      if (res.code === 200) {
        this.comments = res.data
        this.total = res.total
      } else {
        this.$alert(res.msg)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.fly-detail-admin{
  text-align: right;
  border-top: 1px dotted #eaeaea;
  background: #f8f8f8;
}
.fly-detail-info{
  span{
    margin-right: 5px;
  }
}
.fly-admin-box{
  margin-left: 0;
  margin-top: 10px;
}
</style>
